package cn.powertime.evaluation.facade.impl;

import cn.powertime.evaluation.Calculation;
import cn.powertime.evaluation.annotation.Facade;
import cn.powertime.evaluation.entity.*;
import cn.powertime.evaluation.exception.BusinessException;
import cn.powertime.evaluation.facade.CpsTestPaperFacade;
import cn.powertime.evaluation.service.*;
import cn.powertime.evaluation.shiro.ShiroUtils;
import cn.powertime.evaluation.util.CollectionUtils;
import cn.powertime.evaluation.vo.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Facade
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class CpsTestPaperFacadeImpl implements CpsTestPaperFacade {

    @Autowired
    private CpsTestPaperService cpsTestPaperService;
    @Autowired
    private CpsTopicService topicService;
    @Autowired
    private CpsAutomaticService automaticService;
    @Autowired
    private CpsAutomaticTopicService automaticTopicService;
    @Autowired
    private CpsWrongQuestionsService wrongQuestionsService;
    @Autowired
    private CpsExaminationResultService examinationResultService;
    @Autowired
    private CpsExaminationResultDetailsService examinationResultDetailsService;
    @Autowired
    private CpsExaminationPaperService examinationPaperService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Page<RespTestPaperPageVo> courseWorkTestPaperList(ParamPageVo<ReqCourseTestPaperSearchVo> vo) {
        Page<CpsTestPaper> page = new Page<>(vo.getPage().getCurrent(), vo.getPage().getSize());
        return this.cpsTestPaperService.courseWorkTestPaperList(page, vo.getParams());
    }

    @Override
    public RespTestPaperVo courseWorkTopicList(Long sectionId) {
        CpsTestPaper testPaper = this.cpsTestPaperService.selectTestPaperBySectionId(sectionId);
        if (testPaper != null) {
            RespTestPaperVo vo = new RespTestPaperVo();
            vo.setId(testPaper.getId());
            vo.setTitle(testPaper.getTitle());
            vo.setType(testPaper.getTestType());
            vo.setCourseId(testPaper.getCourseId());
            vo.setChapterId(testPaper.getChapterId());
            vo.setSectionId(testPaper.getSectionId());

            List<RespTopicListVo> topicList = getTopicList(testPaper.getId());
            if (CollectionUtils.isNotEmpty(topicList)) {
                Map<Integer, List<RespTopicListVo>> listMap = topicList.stream().collect(Collectors.groupingBy(RespTopicListVo::getType));
                vo.setListMap(listMap);
            }
            return vo;
        }
        return null;
    }

    @Override
    public RespTestPaperVo courseTopicList(Long courseId) {
        CpsTestPaper testPaper = this.cpsTestPaperService.selectTestPaperByCourseId(courseId);
        if (testPaper != null) {
            RespTestPaperVo vo = new RespTestPaperVo();
            vo.setId(testPaper.getId());
            vo.setTitle(testPaper.getTitle());
            vo.setType(testPaper.getTestType());
            vo.setCourseId(testPaper.getCourseId());
            vo.setChapterId(testPaper.getChapterId());
            vo.setSectionId(testPaper.getSectionId());
            vo.setPracticeId(testPaper.getPracticeId());
            vo.setScore(testPaper.getScore());

            List<RespTopicListVo> topicList = getTopicList(testPaper.getId());
            if (CollectionUtils.isNotEmpty(topicList)) {
                Map<Integer, List<RespTopicListVo>> listMap = topicList.stream().collect(Collectors.groupingBy(RespTopicListVo::getType));
                vo.setListMap(listMap);
            }
            return vo;
        }
        return null;
    }

    @Override
    public RespAutomaticVo automaticTopicList() {
        RespAutomaticVo vo = new RespAutomaticVo();
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        String automaticTestPaper = stringRedisTemplate.opsForValue().get(userInfo.getId() + "-automaticTestPaper");
        if (automaticTestPaper != null) {
            JSONObject json = JSONObject.parseObject(automaticTestPaper);
            ReqAutomaticTestPaperVo automaticTestPaperVo = JSON.toJavaObject(json, ReqAutomaticTestPaperVo.class);
            if (automaticTestPaperVo != null) {
                vo.setId(automaticTestPaperVo.getAutomaticId());
                vo.setTitle(automaticTestPaperVo.getTitle());
                List<RespTopicListVo> lists = Lists.newArrayList();
                List<ReqAutomaticTopicListVo> topics = automaticTestPaperVo.getTopicList();
                if (CollectionUtils.isNotEmpty(topics)) {
                    for (ReqAutomaticTopicListVo reqTopic : topics) {
                        RespTopicListVo topic = new RespTopicListVo();
                        topic.setId(reqTopic.getId());
                        topic.setType(reqTopic.getType());
                        topic.setTopicStem(reqTopic.getTopicStem());
                        topic.setOptionA(reqTopic.getOptionA());
                        topic.setOptionB(reqTopic.getOptionB());
                        topic.setOptionC(reqTopic.getOptionC());
                        topic.setOptionD(reqTopic.getOptionD());
                        topic.setUserAnswer(reqTopic.getUserAnswer());
                        lists.add(topic);
                    }
                    Map<Integer, List<RespTopicListVo>> listMap = lists.stream().collect(Collectors.groupingBy(RespTopicListVo::getType));
                    vo.setListMap(listMap);
                }
            }
        } else {
            vo.setId(IdWorker.getId());
            vo.setTitle(userInfo.getUsername() + "-" + LocalDate.now());
            List<RespTopicListVo> list = this.topicService.automaticTopiclist(userInfo.getId());
            List<RespTopicListVo> lists;
            Collections.shuffle(list);
            if (list.size() >= 50) {
                //lists = list.subList(0, 50);
                lists = ImmutableList.copyOf(Iterables.limit(list, 50));
            } else {
                lists = ImmutableList.copyOf(Iterables.limit(list, 2));
            }
            if (CollectionUtils.isNotEmpty(lists)) {
                Map<Integer, List<RespTopicListVo>> listMap = lists.stream().collect(Collectors.groupingBy(RespTopicListVo::getType));
                vo.setListMap(listMap);
            }
        }
        return vo;
    }

    @Override
    public void saveAutomaticTestPaper(ReqAutomaticTestPaperVo vo) {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        stringRedisTemplate.delete(userInfo.getId() + "-automaticTestPaper");//根据key删除缓存
        stringRedisTemplate.opsForValue().set(userInfo.getId() + "-automaticTestPaper", vo.toString());
    }

    @Override
    public Page<RespTestPaperPageVo> simulateExaminationPaperList(PageVo vo) {
        Page<CpsTestPaper> page = new Page<>(vo.getCurrent(), vo.getSize());
        return this.cpsTestPaperService.simulateExaminationPaperList(page);
    }

    @Override
    public RespTestPaperVo testPaperTopicList(Long testPaperId) {
        CpsTestPaper testPaper = this.cpsTestPaperService.getById(testPaperId);
        if (testPaper != null) {
            RespTestPaperVo vo = new RespTestPaperVo();
            vo.setId(testPaper.getId());
            vo.setTitle(testPaper.getTitle());
            vo.setType(testPaper.getTestType());
            vo.setCourseId(testPaper.getCourseId());
            vo.setChapterId(testPaper.getChapterId());
            vo.setSectionId(testPaper.getSectionId());
            vo.setPracticeId(testPaper.getPracticeId());
            vo.setScore(testPaper.getScore());

            List<RespTopicListVo> topicList = getTopicList(testPaperId);
            Map<Integer, List<RespTopicListVo>> listMap = topicList.stream().collect(Collectors.groupingBy(RespTopicListVo::getType));
            vo.setListMap(listMap);
            return vo;
        }
        return null;
    }

    @Override
    public Page<RespTestPaperPageVo> testing(ParamPageVo<ReqTestPaperSearchVo> vo) {
        Page<CpsTestPaper> page = new Page<>(vo.getPage().getCurrent(), vo.getPage().getSize());
        return this.cpsTestPaperService.testing(page, vo.getParams());
    }

    @Override
    public void saveTestPaper(ReqTestPaperVo testPaperVo) {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        stringRedisTemplate.delete(userInfo.getId() + "-" + testPaperVo.getTestPaperId());//根据key删除缓存
        stringRedisTemplate.opsForValue().set(userInfo.getId() + "-" + testPaperVo.getTestPaperId(), testPaperVo.toString());
    }

    @Override
    public CpsExaminationResult submitTestPaper(ReqTestPaperVo testPaperVo) {
         ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        //删除缓存中的答题记录
        stringRedisTemplate.delete(userInfo.getId() + "-" + testPaperVo.getTestPaperId());//根据key删除缓存

        //用户提交的习题列表
        List<ReqTopicListVo> reqTopicList = testPaperVo.getTopicList();
        if (CollectionUtils.isEmpty(reqTopicList)) {
            throw new BusinessException("试卷习题列表为空!");
        }
        Map<Long, List<ReqTopicListVo>> reqTopicMaps = reqTopicList.stream().collect(Collectors.groupingBy(ReqTopicListVo::getId));

        //通过试卷id查找习题列表
        List<RespTopicListVo> topicList = this.cpsTestPaperService.appSelectTopicListByTestPaperId( testPaperVo.getTestPaperId());
        if (CollectionUtils.isEmpty(topicList)) {
            throw new BusinessException("系统中未查询到此试卷下的习题记录!");
        }

        //生成考试结果实体类
        CpsExaminationResult result = new CpsExaminationResult();
        result.setId(IdWorker.getId());
        result.setTestPaperId(testPaperVo.getTestPaperId());
        //result.setUserId(userInfo.getId());
        result.setUserId(1L);
        //生成考试结果详情类
        CpsExaminationResultDetails details = new CpsExaminationResultDetails();
        details.setResultId(result.getId());
        details.setTestPaperId(testPaperVo.getTestPaperId());
        //details.setUserId(userInfo.getId());
        details.setUserId(1L);

        int count = 0;//正确题数量
        double score = 0;//正确题得分
        for (RespTopicListVo respTopic : topicList) {
            ReqTopicListVo reqTopic = new ReqTopicListVo();
            if (CollectionUtils.isNotEmpty(reqTopicMaps)) {
                List<ReqTopicListVo> list = reqTopicMaps.get(respTopic.getId());
                if (CollectionUtils.isNotEmpty(list)) {
                    reqTopic = list.get(0);
                    //如果习题id一致则计算得分
                    if (respTopic.getId().longValue() == reqTopic.getId().longValue()) {
                        //习题类型
                        if (respTopic.getType() == 1) {//单选题
                            if (respTopic.getTopicAnswer().equals(reqTopic.getUserAnswer())) {
                                count += 1;
                                score += respTopic.getScore();
                                details.setIsCorrect(1);
                            } else {
                                details.setIsCorrect(2);
                                //将错题写入错题表
                               // addWrongQuestions(testPaperVo.getTestPaperId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 2) {//多选题
                            int sum = 0;
                            String[] respAnswer = respTopic.getTopicAnswer().split(",");
                            if (reqTopic.getUserAnswer() != null) {
                                for (int i = 0; i < respAnswer.length; i++) {
                                    if (reqTopic.getUserAnswer().indexOf(respAnswer[i]) > -1) {
                                        sum += 1;
                                    }
                                }
                            }
                            if (sum == respAnswer.length) {
                                details.setIsCorrect(1);
                                count += 1;
                                score += respTopic.getScore();
                            } else {
                                details.setIsCorrect(2);
                                //将错题写入错题表
                                //addWrongQuestions(testPaperVo.getTestPaperId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 3) {//判断题
                            if (respTopic.getTopicAnswer().equals(reqTopic.getUserAnswer())) {
                                details.setIsCorrect(1);
                                count += 1;
                                score += respTopic.getScore();
                            } else {
                                details.setIsCorrect(2);
                                //将错题写入错题表
                               // addWrongQuestions(testPaperVo.getTestPaperId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 4) {//问答题
                            int sum = 0;
                            String[] respAnswer = respTopic.getTopicAnswer().split(",");
                            if (reqTopic.getUserAnswer() != null) {
                                for (int i = 0; i < respAnswer.length; i++) {
                                    if (reqTopic.getUserAnswer().indexOf(respAnswer[i]) > -1) {
                                        sum += respTopic.getScore();
                                    }
                                }
                            }
                            if (sum > 0) {
                                details.setIsCorrect(1);
                                count += 1;
                                score += respTopic.getScore();
                            } else {
                                details.setIsCorrect(2);
                                //将错题写入错题表
                                //addWrongQuestions(testPaperVo.getTestPaperId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        }
                    }
                }
            }
            details.setId(IdWorker.getId());
            details.setTopicAnswer(reqTopic.getUserAnswer());
            CpsExaminationPaper cep = this.examinationPaperService.selectExaminationPaper(testPaperVo.getTestPaperId(), reqTopic.getId());
            if (cep != null) {
                details.setExaminationPaperId(cep.getId());
            }
            this.examinationResultDetailsService.save(details);
        }
        String accuracy = Calculation.accuracy(count, topicList.size(), 1);
        result.setScore(new BigDecimal(score));
        result.setAccuracy(accuracy);
        this.examinationResultService.save(result);
        return result;
    }

    @Override
    public CpsExaminationResult AppsubmitTestPaper(ReqTestPaperVo testPaperVo) {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        //删除缓存中的答题记录
        //stringRedisTemplate.delete(userInfo.getId() + "-" + testPaperVo.getTestPaperId());//根据key删除缓存

        //用户提交的习题列表
        List<ReqTopicListVo> reqTopicList = testPaperVo.getTopicList();
        if (CollectionUtils.isEmpty(reqTopicList)) {
            throw new BusinessException("试卷习题列表为空!");
        }
        Map<Long, List<ReqTopicListVo>> reqTopicMaps = reqTopicList.stream().collect(Collectors.groupingBy(ReqTopicListVo::getId));

        //通过试卷id查找习题列表
        List<RespTopicListVo> topicList = this.cpsTestPaperService.appSelectTopicListByTestPaperId( testPaperVo.getTestPaperId());
        if (CollectionUtils.isEmpty(topicList)) {
            throw new BusinessException("系统中未查询到此试卷下的习题记录!");
        }

        //生成考试结果实体类
        CpsExaminationResult result = new CpsExaminationResult();
        result.setId(IdWorker.getId());
        result.setTestPaperId(testPaperVo.getTestPaperId());
        //result.setUserId(userInfo.getId());
        result.setUserId(1L);
        //生成考试结果详情类
        CpsExaminationResultDetails details = new CpsExaminationResultDetails();
        details.setResultId(result.getId());
        details.setTestPaperId(testPaperVo.getTestPaperId());
        //details.setUserId(userInfo.getId());
        details.setUserId(1L);

        int count = 0;//正确题数量
        double score = 0;//正确题得分
        for (RespTopicListVo respTopic : topicList) {
            ReqTopicListVo reqTopic = new ReqTopicListVo();
            if (CollectionUtils.isNotEmpty(reqTopicMaps)) {
                List<ReqTopicListVo> list = reqTopicMaps.get(respTopic.getId());
                if (CollectionUtils.isNotEmpty(list)) {
                    reqTopic = list.get(0);
                    //如果习题id一致则计算得分
                    if (respTopic.getId().longValue() == reqTopic.getId().longValue()) {
                        //习题类型
                        if (respTopic.getType() == 1) {//单选题
                            if (respTopic.getTopicAnswer().equals(reqTopic.getUserAnswer())) {
                                count += 1;
                                score += respTopic.getScore();
                                details.setIsCorrect(1);
                            } else {
                                details.setIsCorrect(2);
                                //将错题写入错题表
                                // addWrongQuestions(testPaperVo.getTestPaperId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 2) {//多选题
                            int sum = 0;
                            String[] respAnswer = respTopic.getTopicAnswer().split(",");
                            if (reqTopic.getUserAnswer() != null) {
                                for (int i = 0; i < respAnswer.length; i++) {
                                    if (reqTopic.getUserAnswer().indexOf(respAnswer[i]) > -1) {
                                        sum += 1;
                                    }
                                }
                            }
                            if (sum == respAnswer.length) {
                                details.setIsCorrect(1);
                                count += 1;
                                score += respTopic.getScore();
                            } else {
                                details.setIsCorrect(2);
                                //将错题写入错题表
                                //addWrongQuestions(testPaperVo.getTestPaperId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 3) {//判断题
                            if (respTopic.getTopicAnswer().equals(reqTopic.getUserAnswer())) {
                                details.setIsCorrect(1);
                                count += 1;
                                score += respTopic.getScore();
                            } else {
                                details.setIsCorrect(2);
                                //将错题写入错题表
                                // addWrongQuestions(testPaperVo.getTestPaperId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 4) {//问答题
                            int sum = 0;
                            String[] respAnswer = respTopic.getTopicAnswer().split(",");
                            if (reqTopic.getUserAnswer() != null) {
                                for (int i = 0; i < respAnswer.length; i++) {
                                    if (reqTopic.getUserAnswer().indexOf(respAnswer[i]) > -1) {
                                        sum += respTopic.getScore();
                                    }
                                }
                            }
                            if (sum > 0) {
                                details.setIsCorrect(1);
                                count += 1;
                                score += respTopic.getScore();
                            } else {
                                details.setIsCorrect(2);
                                //将错题写入错题表
                                //addWrongQuestions(testPaperVo.getTestPaperId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        }
                    }
                }
            }
            details.setId(IdWorker.getId());
            details.setTopicAnswer(reqTopic.getUserAnswer());
            CpsExaminationPaper cep = this.examinationPaperService.selectExaminationPaper(testPaperVo.getTestPaperId(), reqTopic.getId());
            if (cep != null) {
                details.setExaminationPaperId(cep.getId());
            }
            this.examinationResultDetailsService.save(details);
        }
        String accuracy = Calculation.accuracy(count, topicList.size(), 1);
        result.setScore(new BigDecimal(score));
        result.setAccuracy(accuracy);
        this.examinationResultService.save(result);
        return result;
    }

    @Override
    public CpsAutomatic submitAutomaticTestPaper(ReqAutomaticTestPaperVo vo) {
        CpsAutomatic item = this.automaticService.getById(vo.getAutomaticId());
        if (item != null) {
            throw new BusinessException("试卷已经提交过了!");
        }

        //提交智能练习试卷
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        //删除缓存中的答题记录
        stringRedisTemplate.delete(userInfo.getId() + "-automaticTestPaper");//根据key删除缓存

        //习题答案集合
        List<CpsTopic> topicList = Lists.newArrayList();
        //用户提交的习题列表
        List<ReqAutomaticTopicListVo> reqTopicList = vo.getTopicList();
        if (CollectionUtils.isEmpty(reqTopicList)) {
            throw new BusinessException("试卷习题列表为空!");
        }
        for (ReqAutomaticTopicListVo reqTopic : reqTopicList) {
            CpsTopic topic = this.topicService.getById(reqTopic.getId());
            topicList.add(topic);
        }
        Map<Long, List<ReqAutomaticTopicListVo>> reqTopicMaps = reqTopicList.stream().collect(Collectors.groupingBy(ReqAutomaticTopicListVo::getId));

        //生成考试结果实体类
        CpsAutomatic automatic = new CpsAutomatic();
        automatic.setId(vo.getAutomaticId());
        automatic.setUserId(userInfo.getId());
        automatic.setTitle(vo.getTitle());

        //生成考试结果详情类
        CpsAutomaticTopic automaticTopic = new CpsAutomaticTopic();
        automaticTopic.setAutomaticId(automatic.getId());

        int count = 0;//正确题数量
        int score = 0;//总分
        double userScore = 0;//用户得分
        for (CpsTopic respTopic : topicList) {
            if (CollectionUtils.isNotEmpty(reqTopicMaps)) {
                List<ReqAutomaticTopicListVo> list = reqTopicMaps.get(respTopic.getId());
                if (CollectionUtils.isNotEmpty(list)) {
                    ReqAutomaticTopicListVo reqTopic = list.get(0);
                    //如果习题id一致则计算得分
                    score += respTopic.getScoreValue();
                    if (respTopic.getId().longValue() == reqTopic.getId().longValue()) {
                        //习题类型
                        if (respTopic.getType() == 1) {//单选题
                            if (respTopic.getTopicAnswer().equals(reqTopic.getUserAnswer())) {
                                count += 1;
                                userScore += respTopic.getScoreValue();
                                automaticTopic.setIsCorrect(1);
                            } else {
                                automaticTopic.setIsCorrect(2);
                                //将错题写入错题表
                                addWrongQuestions(vo.getAutomaticId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 2) {//多选题
                            int sum = 0;
                            String[] respAnswer = respTopic.getTopicAnswer().split(",");
                            if (reqTopic.getUserAnswer() != null) {
                                for (int i = 0; i < respAnswer.length; i++) {
                                    if (reqTopic.getUserAnswer().indexOf(respAnswer[i]) > -1) {
                                        sum += 1;
                                    }
                                }
                            }
                            if (sum == respAnswer.length) {
                                automaticTopic.setIsCorrect(1);
                                count += 1;
                                userScore += respTopic.getScoreValue();
                            } else {
                                automaticTopic.setIsCorrect(2);
                                //将错题写入错题表
                                addWrongQuestions(vo.getAutomaticId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 3) {//判断题
                            if (respTopic.getTopicAnswer().equals(reqTopic.getUserAnswer())) {
                                automaticTopic.setIsCorrect(1);
                                count += 1;
                                userScore += respTopic.getScoreValue();
                            } else {
                                automaticTopic.setIsCorrect(2);
                                //将错题写入错题表
                                addWrongQuestions(vo.getAutomaticId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        } else if (respTopic.getType() == 4) {//问答题
                            int sum = 0;
                            String[] respAnswer = respTopic.getTopicAnswer().split(",");
                            if (reqTopic.getUserAnswer() != null) {
                                for (int i = 0; i < respAnswer.length; i++) {
                                    if (reqTopic.getUserAnswer().indexOf(respAnswer[i]) > -1) {
                                        sum += respTopic.getScoreValue();
                                    }
                                }
                            }
                            if (sum > 0) {
                                automaticTopic.setIsCorrect(1);
                                count += 1;
                                userScore += respTopic.getScoreValue();
                            } else {
                                automaticTopic.setIsCorrect(2);
                                //将错题写入错题表
                                addWrongQuestions(vo.getAutomaticId(), userInfo, reqTopic.getId(), reqTopic.getUserAnswer());
                            }
                        }
                    }
                    automaticTopic.setId(IdWorker.getId());
                    automaticTopic.setTopicId(respTopic.getId());
                    automaticTopic.setScore(respTopic.getScoreValue());
                    automaticTopic.setTopicAnswer(reqTopic.getUserAnswer());
                    this.automaticTopicService.save(automaticTopic);
                }
            }
        }
        String accuracy = Calculation.accuracy(count, topicList.size(), 1);
        automatic.setScore(score);
        automatic.setUserScore(new BigDecimal(userScore));
        automatic.setAccuracy(accuracy);
        this.automaticService.save(automatic);
        return automatic;
    }

    @Override
    public AppRespTestPaperVo  courseWorkTopicListApp(Long sectionId) {
        CpsTestPaper testPaper = this.cpsTestPaperService.selectTestPaperBySectionId(sectionId);
        if (testPaper != null) {
            AppRespTestPaperVo vo = new AppRespTestPaperVo();
            vo.setId(testPaper.getId());
            vo.setTitle(testPaper.getTitle());
            vo.setType(testPaper.getTestType());
            vo.setCourseId(testPaper.getCourseId());
            vo.setChapterId(testPaper.getChapterId());
            vo.setSectionId(testPaper.getSectionId());

            List<RespTopicListVo> topicList = getTopicListApp(testPaper.getId());
           // List<RespTopicListVo> listVos=new ArrayList<>();
            Map<Integer, RespTopicListVo> listMap=new HashMap<>();
            RespTopicListVo vo1;
            int f=0;
            if (CollectionUtils.isNotEmpty(topicList)) {
                for(int i=0;i<topicList.size();i++){
                    vo1=new RespTopicListVo();
                    //listMap.put(f,listVos);
                    f++;
                    vo1.setId(topicList.get(i).getId());
                    vo1.setCollect(topicList.get(i).getCollect());
                    vo1.setOptionA(topicList.get(i).getOptionA());
                    vo1.setOptionB(topicList.get(i).getOptionB());
                    vo1.setOptionC(topicList.get(i).getOptionC());
                    vo1.setOptionD(topicList.get(i).getOptionD());
                    vo1.setScore(topicList.get(i).getScore());
                    vo1.setTopicAnswer(topicList.get(i).getTopicAnswer());
                    vo1.setType(topicList.get(i).getType());
                    vo1.setUserAnswer(topicList.get(i).getUserAnswer());
                    vo1.setTopicStem(topicList.get(i).getTopicStem());
                    listMap.put(f,vo1);
                }
                Map<Long, List<RespTopicListVo>> listMaps = topicList.stream().collect(Collectors.groupingBy(RespTopicListVo::getId));
                vo.setListMap(listMap);
            }
            return vo;
        }
        return null;
    }

    /**
     * 将错题写入错题表
     *
     * @param testPaperId 试卷id
     * @param userInfo    用户信息
     * @param topicId     习题id
     * @param userAnswer  用户答案
     */
    private void addWrongQuestions(Long testPaperId, ShiroUserInfo userInfo, Long topicId, String userAnswer) {
        Boolean flag = this.wrongQuestionsService.checkWrongTopicOnly(userInfo.getId(), topicId);
        if (flag == false) {
            CpsWrongQuestions wrongQuestions = new CpsWrongQuestions();
            wrongQuestions.setId(IdWorker.getId());
            wrongQuestions.setUserId(userInfo.getId());
            wrongQuestions.setTestPaperId(testPaperId);
            wrongQuestions.setTopicId(topicId);
            wrongQuestions.setTopicAnswer(userAnswer);
            this.wrongQuestionsService.save(wrongQuestions);
        }
    }

    /**
     * 查询缓存中是否保存当前试卷进度
     *
     * @param testPaperId 试卷id
     * @return List
     */
    private List<RespTopicListVo> getTopicList(Long testPaperId) {
        List<RespTopicListVo> topicList = this.cpsTestPaperService.selectTopicListByTestPaperId(/*ShiroUtils.getUserInfo().getId()*/null, testPaperId);
        if (CollectionUtils.isNotEmpty(topicList)) {
            ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
            String userTestPaper = stringRedisTemplate.opsForValue().get(userInfo.getId() + "-" + testPaperId);
            if (userTestPaper != null) {
                JSONObject userJson = JSONObject.parseObject(userTestPaper);
                ReqTestPaperVo testPaperVo = JSON.toJavaObject(userJson, ReqTestPaperVo.class);
                List<ReqTopicListVo> topics = testPaperVo.getTopicList();
                //将缓存中的习题列表转为map
                Map<Long, List<ReqTopicListVo>> reqTopicMaps = new HashMap<>();
                if (CollectionUtils.isNotEmpty(topics)) {
                    reqTopicMaps = topics.stream().collect(Collectors.groupingBy(ReqTopicListVo::getId));
                }
                for (RespTopicListVo respTopic : topicList) {
                    //通过习题id查询缓存中习题对象
                    if (CollectionUtils.isNotEmpty(reqTopicMaps)) {
                        List<ReqTopicListVo> list = reqTopicMaps.get(respTopic.getId());
                        if (CollectionUtils.isNotEmpty(list)) {
                            ReqTopicListVo reqTopic = list.get(0);
                            if (reqTopic != null) {
                                if (respTopic.getId().longValue() == reqTopic.getId().longValue()) {
                                    respTopic.setUserAnswer(reqTopic.getUserAnswer());
                                }
                            }
                        }
                    }
                }
            }
        }
        return topicList;
    }

    private List<RespTopicListVo> getTopicListApp(Long testPaperId) {
        List<RespTopicListVo> topicList = this.cpsTestPaperService.appSelectTopicListByTestPaperId(testPaperId);
      /*  if (CollectionUtils.isNotEmpty(topicList)) {
            ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
            String userTestPaper = stringRedisTemplate.opsForValue().get(userInfo.getId() + "-" + testPaperId);
            if (userTestPaper != null) {
                JSONObject userJson = JSONObject.parseObject(userTestPaper);
                ReqTestPaperVo testPaperVo = JSON.toJavaObject(userJson, ReqTestPaperVo.class);
                List<ReqTopicListVo> topics = testPaperVo.getTopicList();
                //将缓存中的习题列表转为map
                Map<Long, List<ReqTopicListVo>> reqTopicMaps = new HashMap<>();
                if (CollectionUtils.isNotEmpty(topics)) {
                    reqTopicMaps = topics.stream().collect(Collectors.groupingBy(ReqTopicListVo::getId));
                }
                for (RespTopicListVo respTopic : topicList) {
                    //通过习题id查询缓存中习题对象
                    if (CollectionUtils.isNotEmpty(reqTopicMaps)) {
                        List<ReqTopicListVo> list = reqTopicMaps.get(respTopic.getId());
                        if (CollectionUtils.isNotEmpty(list)) {
                            ReqTopicListVo reqTopic = list.get(0);
                            if (reqTopic != null) {
                                if (respTopic.getId().longValue() == reqTopic.getId().longValue()) {
                                    respTopic.setUserAnswer(reqTopic.getUserAnswer());
                                }
                            }
                        }
                    }
                }
            }
        }*/
        return topicList;
    }
}
